#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 数据来源: https://github.com/selva86/datasets

# 1 Matplotlib可视化最有价值的50个图表
# 1.1 介绍
'''
这些图表根据可视化目标的7个不同情境进行分组.
有效图表的重要特征：
• 在不歪曲事实的情况下传达正确和必要的信息。
• 设计简单，您不必太费力就能理解它。
• 从审美⻆度支持信息而不是掩盖信息。
• 信息没有超负荷
'''

# 1. 准备工作
# 单独的图表,重新设置显示要素.
# pip install brewer2mpl
# pip install seaborn
import numpy as np 
import pandas as pd 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import seaborn as sns 
import warnings; warnings.filterwarnings(action='once')

"""
large = 22; med = 16; small = 12
params = {'axes.titlesize': large,
          'legend.fontsize': med,
          'figure.figsize': (16,10),
          'axes.labelsize': med,
          'axes.titlesize': med,
          'xtick.labelsize': med,
          'ytick.labelsize': med,
          'figure.titlesize': large}

plt.rcParams.update(params)
plt.style.use('seaborn-whitegrid')
sns.set_style("white")

# Version
# print(mpl.__version__) # > 3.0.0
# print(sns.__version__) # > 0.9.0
"""


# 1.3 关联(Correlation)
# 关联图表用于可视化2个或更多变量之间的关系. 一个变量如何相对于另一个变化.
# 1.3.1 散点图(Scatter plot)
# 散点图是用于研究两个变量之间关系的经典的和基本的图表。如果数据中有多个组，则可能需要以不同颜色,可视化每个组。
# 在 matplotlib 中，可以使用 plt.scatterplot()方便地执行此操作。
"""
# Import dataset
midwest = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/midwest_filter.csv")

categories = np.unique(midwest['category'])
colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))]

# Draw Plot for Each Category
plt.figure(figsize=(16,10),dpi=80,facecolor='w',edgecolor='k')
for i, category in enumerate(categories):
    plt.scatter('area','poptotal',data=midwest.loc[midwest.category==category,:], \
        s = 20,cmap=colors[i],label=str(category))

plt.gca().set(xlim=(0.0,0.1),ylim=(0,90000),xlabel='Area',ylabel='Population')
plt.xticks(fontsize=12); plt.yticks(fontsize=12)
plt.title("Scatterplot of Midwest Area vs Population", fontsize=22)
plt.legend(fontsize=12)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\Scatterplot1.png")
plt.show()
"""





# 1.3.2 带边界的气泡图(Bubble plot with Encircling)
# encircle() 来使边界显示出来.
"""
from matplotlib import patches
from scipy.spatial import ConvexHull
import warnings; warnings.simplefilter('ignore')
sns.set_style("white")

# Step 1: Prepare Data
midwest = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\midwest_filter.csv")

# As many colors as there are unique midwest['category']
categories = np.unique(midwest['category'])
colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))]

# Step 2: Draw Scatterplot with unique color for each category
fig = plt.figure(figsize=(16,10),dpi=80, facecolor='w',edgecolor='k')

for i,category in enumerate(categories):
    plt.scatter('area','poptotal',data=midwest.loc[midwest.category==category,:],\
    s='dot_size',cmap=colors[i],label=str(category),edgecolors='black',linewidths=.5)

# Step 3: Encircling
def encircle(x,y,ax=None,**kw):
    if not ax: ax=plt.gca()
    p = np.c_[x,y]
    hull = ConvexHull(p)
    poly = plt.Polygon(p[hull.vertices,:],**kw)
    ax.add_patch(poly)

# Select data to be encircled
midwest_encircle_data = midwest.loc[midwest.state=='IN',:]

# Draw polygon surrounding vertices
encircle(midwest_encircle_data.area,midwest_encircle_data.poptotal,ec="firebrick",fc="none",linewidth=1.5)

# Step 4: Decorations
plt.gca().set(xlim=(0.0,0.1),ylim=(0,90000),\
        xlabel="Area",ylabel='Population')

plt.xticks(fontsize=12); plt.yticks(fontsize=12)
plt.title("Bubble Plot with Encircling",fontsize=22)
plt.legend(fontsize=12)
# plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\bubbleplot.png")
plt.show()
"""



# 1.3.3  带线性回归最佳拟合线的散点图(Scatter plot with linear regression line of best fit)
# 下图显示了数据中各组之间最佳拟合线的差异. 
# 要禁用分组并仅为整个数据集绘制一条最佳拟合线,请从下面的sns.lmplot()调用中删除hue='cyl'参数.
# pip install statsmodels,  patsy
"""
from matplotlib import patches
from scipy.spatial import ConvexHull
import warnings; warnings.simplefilter('ignore')
from statsmodels.robust.robust_linear_model import RLM
from patsy import dmatrices, NAAction

df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")
df_select = df.loc[df.cyl.isin([4,8]),:]

# Plot
sns.set_style("white")
gridobj = sns.lmplot(x="displ",y="hwy",hue="cyl",data=df_select, \
    height=7,aspect=1.6,robust=True,palette='tab10',\
        scatter_kws=dict(s=60,linewidths=.7,edgecolors='black'))

gridobj.set(xlim=(0.5,7.5),ylim=(0,50))
plt.title("Scatterplot with line of best fit grouped by number of cylinders",fontsize=20)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\regression.png")
plt.show()
"""


# 针对每列绘制线性回归线
# 在每列中显示每个组的最佳拟合线. 可以通过sns.lmplot()中设置col=groupingcolumn参数来实现.
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mpg_ggplot2.csv")
df_select = df.loc[df.cyl.isin([4,8]),:]

# Each line in its own column
sns.set_style("white")
gridobj = sns.lmplot(x="displ",y="hwy",
                data=df_select,
                height=7,
                robust=True,
                palette='Set1',
                col="cyl",
                scatter_kws=dict(s=60,linewidth=.7,edgecolors='black'))

# Decorations
gridobj.set(xlim=(0.5,7.5),ylim=(0,50))
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\xianxinghuiguixian.png")
plt.show()
# 带线性回归最佳拟合线的散点图.
